package com.afish.syl.lib.api.core.afishpublic.common;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
import android.util.Log;

import java.util.List;

/**
 * 常用方法收集类
 * 作者：苏逸龙 on 2015-08-31 09:20
 * QQ：317616660
 */
public class CommonUtils {

    // 启动APK的默认Activity

    /**
     * MethodName:startApkActivity
     * Method description
     *
     *
     * @param ctx
     * @param packageName
     */
    public static void startApkActivity(final Context ctx, String packageName) {
        PackageManager pm = ctx.getPackageManager();
        PackageInfo    pi;

        try {
            pi = pm.getPackageInfo(packageName, 0);

            Intent intent = new Intent(Intent.ACTION_MAIN, null);

            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setPackage(pi.packageName);

            List<ResolveInfo> apps = pm.queryIntentActivities(intent, 0);
            ResolveInfo       ri   = apps.iterator().next();

            if (ri != null) {
                String className = ri.activityInfo.name;

                intent.setComponent(new ComponentName(packageName, className));
                ctx.startActivity(intent);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("startActivity", String.valueOf(e));
        }
    }



    /**
     * MethodName:getScreenPhysicalSize
     * Method description
     * 精确获取屏幕尺寸（例如：3.5、4.0、5.0寸屏幕）
     *
     * @param ctx
     *
     * @return
     */
    public static double getScreenPhysicalSize(Activity ctx) {
        DisplayMetrics dm = new DisplayMetrics();

        ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);

        double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));

        return diagonalPixels / (160 * dm.density);
    }



    /**
     * MethodName:isTablet
     * Method description
     * 一般是7寸以上是平板
     * 判断是否是平板（官方用法）
     *
     * @param context
     *
     * @return
     */
    public static boolean isTablet(Context context) {
        return (context.getResources()
                       .getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }
}


//~ Formatted by syl